<template>
    <div class="flex-container" :style="{ height: clientHeight + 'px' }">
        <div class="title">发票助手</div>
        <el-upload
            ref="upload"
            drag
            :limit="1"
            action="-"
            :auto-upload="false"
            accept=".pdf"
            :show-file-list="false"
            :on-change="onChange"
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-button type="primary" @click="handleBack" size="medium" round style="margin-top: 25px">返回主页</el-button>
    </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.min.js'
pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js'
import * as XLSX from 'xlsx'
export default {
    data() {
        return {
            clientHeight: document.documentElement.clientHeight || document.body.clientHeight,
            url: '',
            filename: ''
        }
    },
    methods: {
        async handleData() {
            var threshold = 3 // 阀值
            var pdf = await pdfjsLib.getDocument(this.url).promise
            let result = []
            let numPages = pdf.numPages
            let that = this
            for (let i = 1; i <= numPages; i++) {
                pdf.getPage(i).then(function (page) {
                    page.getTextContent().then(function (textContent) {
                        let array = textContent.items.sort(function (front, after) {
                            let frontX = Math.round(front.transform[4])
                            let frontY = Math.round(front.transform[5])
                            let afterX = Math.round(after.transform[4])
                            let afterY = Math.round(after.transform[5])
                            if (frontY > afterY && frontX < afterX) {
                                return afterY - frontY
                            } else if (frontY == afterY) {
                                return frontX - afterX
                            } else if (frontY > afterY && frontX >= afterX) {
                                if (frontY - afterY < threshold) {
                                    return frontX - afterX
                                }
                                return afterY - frontY
                            } else if (frontY < afterY && frontX >= afterX) {
                                return afterY - frontY
                            } else if (frontY < afterY && frontX < afterX) {
                                return afterY - frontY
                            } else {
                                console.log('其他')
                            }
                        })
                        var fullText = ''
                        for (var i = 0; i < array.length; i++) {
                            fullText += array[i].str
                        }
                        fullText = fullText
                            .replace(/\s+/g, '')
                            .replace(/：/g, ':')
                            .replace(/（/g, '(')
                            .replace(/）/g, ')')
                        console.log(fullText)
                        let category = ''
                        if (fullText.indexOf('校验码') > -1) {
                            category = 'old'
                        } else {
                            category = 'new'
                        }
                        if (category === 'old') {
                        } else {
                        }
                        // 开票日期
                        const dateRegex = new RegExp('开票日期:(\\d{4}年\\d{2}月\\d{2}日)')
                        const dateMatcher = fullText.match(dateRegex)
                        result.push(dateMatcher[1])
                        // 发票代码
                        const codeRegex = new RegExp('发票代码:(\\d{12})')
                        const codeMatcher = fullText.match(codeRegex)
                        result.push(codeMatcher[1])
                        // 发票号码
                        const numberRegex = new RegExp('发票号码:(\\d{8})')
                        const numberMatcher = fullText.match(numberRegex)
                        result.push(numberMatcher[1])
                        // 购买方名称
                        const buyerNameRegex = new RegExp('名称:(\\\S*)购')
                        const buyerNameMatcher = fullText.match(buyerNameRegex)
                        result.push(buyerNameMatcher[1])
                        // 购买方纳税人识别号
                        const buyerCodeRegex = new RegExp('纳税人识别号:(\\\S{18})')
                        const buyerCodeMatcher = fullText.match(buyerCodeRegex)
                        result.push(buyerCodeMatcher[1])
                        // 销售方名称
                        const sellerNameRegex = new RegExp('名称:(\\\S*)购')
                        const sellerNameMatcher = fullText.match(sellerNameRegex)
                        result.push(sellerNameMatcher[1])
                        // 销售方纳税人识别号
                        const sellerCodeRegex = new RegExp('纳税人识别号:(\\\S{18})售')
                        const sellerCodeMatcher = fullText.match(sellerCodeRegex)
                        result.push(sellerCodeMatcher[1])
                        result.push(13123)
                        const data = [
                            [
                                '开票日期',
                                '发票代码',
                                '发票号码',
                                '购买方名称',
                                '购买方纳税人识别号',
                                '销售方名称',
                                '销售方纳税人识别号',
                                '价税合计'
                            ]
                        ]
                        data.push(result)
                        // 将二维数组转换为工作表对象
                        const ws = XLSX.utils.aoa_to_sheet(data)
                        // 创建一个新的工作簿对象
                        const wb = XLSX.utils.book_new()
                        // 将工作表对象添加到工作簿中，'Sheet1'为工作表的名称
                        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
                        // 将工作簿数据写入文件，'exported_data.xlsx'为导出文件的名称
                        XLSX.writeFile(wb, that.filename + '_invoice.xlsx')
                    })
                })
            }
        },
        onChange(file) {
            this.filename = file.name.split('.')[0]
            let pattern = /.(pdf)$/g
            if (!pattern.test(file.name)) {
                this.$message.error('只能上传pdf文件')
                return false
            }
            this.url = URL.createObjectURL(file.raw)
            this.handleData()
            this.$refs.upload.clearFiles()
            return true
        },
        handleBack() {
            this.$router.replace('/')
        }
    }
}
</script>

<style scoped>
.flex-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.el-button--primary {
    background-color: #505587;
    border-color: #505587;
}
.el-upload-dragger .el-upload__text em {
    color: #505587;
}
.title {
    font-size: 24px;
    line-height: 34px;
    color: #33333b;
    font-weight: 600;
    margin-bottom: 25px;
}
</style>
